import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  //在本地运行
  baseURL: 'http://127.0.0.1:3666/api',
  // baseURL: '/api',
  timeout: 60000, // 增加超时时间以支持文件上传
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('响应错误:', error)
    const message = error.response?.data?.error || error.message || '网络错误'
    ElMessage.error(message || '请求失败')
    return Promise.reject(error)
  }
)

// API接口定义
export const apiService = {
  // 数据库表管理
  getTables: () => api.get('/database/tables'),
  getTableDetail: (tableName) => api.get(`/database/tables/${encodeURIComponent(tableName)}`),
  createTable: (tableData) => api.post('/database/tables', tableData),
  deleteTable: (tableName) => api.delete(`/database/tables/${encodeURIComponent(tableName)}`),
  addColumn: (tableName, columnData) => api.post(`/database/tables/${encodeURIComponent(tableName)}/columns`, columnData),
  deleteColumn: (tableName, columnName) => api.delete(`/database/tables/${encodeURIComponent(tableName)}/columns/${encodeURIComponent(columnName)}`),
  
    // 新增：更新表名和备注接口
  updateTableInfo: (oldName, newName, comment) =>
    api.post('/database/updateTableInfo', { oldName, newName, comment }),

  // 数据管理
  getTableData: (tableName, params = {}) => api.get(`/data/${encodeURIComponent(tableName)}`, { params }),
  createRecord: (tableName, data) => api.post(`/data/${encodeURIComponent(tableName)}`, data),
  updateRecord: (tableName, id, data) => api.put(`/data/${encodeURIComponent(tableName)}/${id}`, data),
  deleteRecord: (tableName, id) => api.delete(`/data/${encodeURIComponent(tableName)}/${id}`),
  
  // 文件导入导出
  importExcel: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/import-excel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  getImportTemplate: () => api.get('/import-template'),
  exportTable: (tableName) => {
    return api.get(`/export/${encodeURIComponent(tableName)}`, {
      responseType: 'blob',  // 指定响应类型为二进制数据
      transformResponse: [(data) => data]  // 禁用默认的JSON转换
    });
  },
  importTable: (tableName, data) => api.post(`/import/${encodeURIComponent(tableName)}`, { data }),
  
  // 辅助功能
  getDataTypes: () => api.get('/database/data-types'),
  getStatistics: () => api.get('/statistics'),
  
  // 健康检查
  healthCheck: () => api.get('/health'),

  // 行政区划树
  getRegionTree: () => api.get('/regions/tree')

  
}

export default api